package com.example.baiguangsystem.interceptor;

import com.alibaba.fastjson.JSON;
import com.example.baiguangsystem.entity.User;
import com.example.baiguangsystem.vo.ResultType;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

/**
 * 设置超级用户的拦截器，专门用于拦截不是超级用户的操作
 *
 * @Author: 27641
 * @ProjectName: BaiGuangSystem
 * @Date: 2022/02/06/23:11
 * @noinspection SpellCheckingInspection
 */
@Component
public class RootUserInterceptor implements HandlerInterceptor {

    /**
     * 如果是root用户才可以进行放行
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            HttpSession session = request.getSession();
            for (Cookie cookie : cookies) {
                User user = (User) session.getAttribute(cookie.getName());
                if ((user != null) && (user.getUserName().equals("root"))) {
                    return true;
                }
            }
        }
        ResultType<?> fail = ResultType.fail("需要root权限才可以进行该项操作!");
        sendHintMessages(fail, response);
        return false;
    }

    /**
     * 返回信息
     *
     * @param resultMessage 返回信息的封装
     * @param response      响应对象
     */
    @SneakyThrows
    public void sendHintMessages(ResultType resultMessage, HttpServletResponse response) {
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();
        String toJSONString = JSON.toJSONString(resultMessage);
        writer.println(toJSONString);
        writer.flush();
        writer.close();
    }
}
